package com.code.question5.impl;

import com.alibaba.fastjson.JSON;
import com.code.question5.base.ResponseType;
import com.code.question5.model.ResponseMessage;
import com.code.question5.model.User;
import com.code.question5.service.IUserService;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户操作服务类
 */
public class UserServiceImpl implements IUserService, Serializable {
    private static List<User> userList = new ArrayList<>();

    /**
     * 登录
     * @param u
     * @return
     */
    @Override
    public String Login(User u) {
        if (userList.size() == 0) {
            return JSON.toJSONString(new ResponseMessage(ResponseType.FAIL, "登录失败"));
        }
        User user = userList.stream().filter(s -> s.getName().equals(u.getName())).findFirst().orElse(null);
        if (user != null && user.getPassword().equals(u.getPassword())) {
            return JSON.toJSONString(new ResponseMessage(ResponseType.SUCCESS, "登录成功"));
        } else {
            return JSON.toJSONString(new ResponseMessage(ResponseType.FAIL, "登录失败"));
        }
    }

    /**
     * 注册
     * @param u
     * @return
     */
    @Override
    public String Register(User u) {
        User user = userList.stream().filter(s -> s.getName().equals(u.getName())).findFirst().orElse(null);
        if (user == null) {
            userList.add(u);
            File file = new File("");
            String projectPath = null;
            ObjectOutputStream oos = null;
            try {
                projectPath = file.getCanonicalPath();
                String diskPath = projectPath.substring(0, projectPath.indexOf("\\") + 1);
                File userFile = new File(diskPath + "Repository\\user.txt");
                if (!userFile.exists()) {
                    userFile.getParentFile().mkdirs();
                }
                oos = new ObjectOutputStream(new FileOutputStream(userFile));
                oos.writeObject(userList);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != oos) {
                    try {
                        oos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return JSON.toJSONString(new ResponseMessage(ResponseType.SUCCESS, "注册成功"));
        } else {
            return JSON.toJSONString(new ResponseMessage(ResponseType.FAIL, "注册失败,该用户已存在"));
        }
    }

    /**
     * 缓存用户信息
     * @param u
     */
    public void PostUser(User u) {
        userList.add(u);
    }
}
